'use strict';

import React from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core/styles'
import {
  Dialog,
  AppBar,
  Toolbar,
  IconButton,
  Typography,
  Button,
} from '@material-ui/core'
import CloseIcon from '@material-ui/icons/Close'

import PatientBlock from './patient'
import DiagnosisBlock from './diagnosis'
import config from '../../../controller/config'

const electron = window.require('electron')

const styles = theme => ({
  root: {
    padding: 16
  },
  appBar: {
    position: 'relative',
  },
  flex: {
    flex: 1,
  },
  iframe: {
    height: '100%'
  }
});

class CheckDesk extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      _id: this.props.match.params._id,
      dialog: false,
      ID: ''
    }
  }

  componentDidMount() {
    electron.ipcRenderer.on('saved', (e, arg) => {
      this.setState({
        dialog: true,
        ID: arg.prescription.ID,
        patient: arg.patient
      })
    })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.match.params._id != undefined) {
      this.setState({
        _id: nextProps.match.params._id
      })
    }
  }

  handlePrint() {

  }
  
  render() {
    const { classes } = this.props
    return (
      <div className={classes.root}>
        <PatientBlock
          _id={this.state._id}
          patient={this.state.patient || {}}
          ref={(r) => this.patient_ref = r}
        />
        <DiagnosisBlock
          _id={this.state._id}
        />
        <Dialog
          open={this.state.dialog}
          fullScreen
          onClose={() => this.setState({dialog: false})}
        >
          <AppBar className={classes.appBar}>
            <Toolbar>
              <IconButton color="inherit" onClick={() => this.setState({ dialog: false})} aria-label="Close">
                <CloseIcon />
              </IconButton>
              <Typography variant="h6" color="inherit" className={classes.flex}>
                {this.state.ID}
              </Typography>
              <Button color="inherit" onClick={() => this.handlePrint()}>
                打印
              </Button>
            </Toolbar>
          </AppBar>
          <iframe className={classes.iframe} src={`${config.baseUrl}api/prescription?ID=${this.state.ID}`} />
        </Dialog>
      </div>
    )
  }
}

CheckDesk.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(CheckDesk);